// src/services/points.js - 积分系统服务

import { get, post } from './api';
import {
  getUserPoints as localGetUserPoints,
  updateUserPoints as localUpdateUserPoints,
  dailySignIn as localDailySignIn,
  calculateUserTitle as localCalculateUserTitle,
  exchangeStarCoinsForUpload as localExchangeStarCoinsForUpload,
  exchangeMagicForUpload as localExchangeMagicForUpload,
  POINT_SYSTEM,
  initUserPoints
} from '../utils/localStorage';

/**
 * 获取用户积分信息
 * @param {string} username - 用户名
 * @returns {Promise} - 积分信息
 */
export const getUserPoints = async (username) => {
  try {
    const response = await get(`/users/${username}/points`);
    return response;
  } catch (error) {
    console.warn('获取用户积分API连接失败，使用本地存储:', error);

    const points = localGetUserPoints(username);
    return {
      success: true,
      data: { points }
    };
  }
};

/**
 * 每日签到
 * @param {string} username - 用户名
 * @returns {Promise} - 签到结果
 */
export const dailySignIn = async (username) => {
  try {
    // 连接后端签到接口 POST /api/user/signin
    const response = await post('/api/user/signin');

    // 后端返回格式：{code: 200, message: "签到成功！获得 40 魔力值。", data: null}
    if (response.code === 200) {
      return {
        success: true,
        message: response.message,
        data: { magicValue: 40 } // 后端增加40魔力值
      };
    } else {
      return {
        success: false,
        message: response.message || '签到失败',
        data: null
      };
    }
  } catch (error) {
    console.warn('每日签到API连接失败，使用本地存储:', error);

    const result = localDailySignIn(username);
    return {
      success: result.success,
      message: result.message,
      data: result.success ? { starCoins: result.starCoins } : null
    };
  }
};

/**
 * 检查今日签到状态
 * @param {string} username - 用户名
 * @returns {Promise} - 签到状态
 */
export const getSignInStatus = async (username) => {
  try {
    // 连接后端签到状态查询接口 GET /api/user/signin/status
    const response = await get('/api/user/signin/status');

    if (response.code === 200) {
      // 后端返回 "已经点赞过" 或 "还未点赞"
      const hasSignedToday = response.data === "已经点赞过";
      return {
        success: true,
        hasSignedToday,
        message: response.data
      };
    } else {
      return {
        success: false,
        hasSignedToday: false,
        message: response.message || '查询签到状态失败'
      };
    }
  } catch (error) {
    console.warn('查询签到状态API连接失败，使用本地存储:', error);

    // 回退到本地存储逻辑
    const today = new Date().toDateString();
    const lastSignInDate = localStorage.getItem('starrypt_last_signin');
    const hasSignedToday = lastSignInDate === today;

    return {
      success: true,
      hasSignedToday,
      message: hasSignedToday ? '今日已签到' : '今日未签到'
    };
  }
};

/**
 * 获取用户称号
 * @param {string} username - 用户名
 * @returns {Promise} - 用户称号信息
 */
export const getUserTitle = async (username) => {
  try {
    const response = await get(`/users/${username}/title`);
    return response;
  } catch (error) {
    console.warn('获取用户称号API连接失败，使用本地存储:', error);

    const points = localGetUserPoints(username);
    const title = localCalculateUserTitle(points.totalLikes);

    return {
      success: true,
      data: { title }
    };
  }
};

/**
 * 星币兑换上传量
 * @param {string} username - 用户名
 * @param {number} starCoins - 兑换的星币数量
 * @returns {Promise} - 兑换结果
 */
export const exchangeStarCoinsForUpload = async (username, starCoins) => {
  try {
    const response = await post(`/users/${username}/exchange-star-coins`, { starCoins });
    return response;
  } catch (error) {
    console.warn('星币兑换API连接失败，使用本地存储:', error);

    const result = localExchangeStarCoinsForUpload(username, starCoins);
    return {
      success: result.success,
      message: result.message,
      data: result.success ? { uploadAmount: result.uploadAmount } : null
    };
  }
};

/**
 * 魔力值兑换上传量
 * @param {string} username - 用户名
 * @param {number} magicValue - 兑换的魔力值数量
 * @returns {Promise} - 兑换结果
 */
export const exchangeMagicForUpload = async (username, magicValue) => {
  try {
    const response = await post(`/users/${username}/exchange-magic`, { magicValue });
    return response;
  } catch (error) {
    console.warn('魔力值兑换API连接失败，使用本地存储:', error);

    const result = localExchangeMagicForUpload(username, magicValue);
    return {
      success: result.success,
      message: result.message,
      data: result.success ? { uploadAmount: result.uploadAmount } : null
    };
  }
};

/**
 * 获取积分系统配置
 * @returns {Promise} - 系统配置
 */
export const getPointSystemConfig = async () => {
  try {
    const response = await get('/system/point-config');
    return response;
  } catch (error) {
    console.warn('获取积分系统配置API连接失败，使用本地配置:', error);

    return {
      success: true,
      data: { config: POINT_SYSTEM }
    };
  }
};

export default {
  getUserPoints,
  dailySignIn,
  getSignInStatus,
  getUserTitle,
  exchangeStarCoinsForUpload,
  exchangeMagicForUpload,
  getPointSystemConfig
};
